import { useState, useRef } from 'react';
import { useBoolean } from 'ahooks';
import { Space, App, Button, Typography } from 'antd';
import { getUserList, DeleteUser } from 'src/api/modules/user';
import Table from 'src/components/Table';
import PermissionButton from 'src/components/Permission';
import { IUserInfo } from 'src/interface';
import { schemas, columns } from './data';
import UserModal from './UserModal';

const Link = Typography.Link;

export default function RoleManage() {
  const [visible, { setTrue, setFalse }] = useBoolean(false);

  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [data, setData] = useState<IUserInfo | null>(null);
  const tableRef = useRef<{ onRefresh: () => void; data: any[] }>({
    onRefresh: () => {},
    data: [],
  });

  const { modal } = App.useApp();

  const setVisibleHandle = (data?: IUserInfo) => {
    setTrue();
    setData(data ? data : null);
  };

  const onDelete = async (ids: string[]) => {
    modal.confirm({
      title: '删除用户',
      content: `确定${ids.length === 1 ? '删除' : '批量删除'}用户吗？`,
      onOk: async () => {
        try {
          await DeleteUser(ids);
          tableRef.current.onRefresh();
        } catch (err) {
          console.log(err);
        }
      },
    });
  };

  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };

  return (
    <div className="m-[16px] rounded-md min-[calc(100vh - 32px)]">
      <Table
        ref={tableRef}
        downloadName="角色管理"
        formProps={{ schemas }}
        rowSelection={{
          selectedRowKeys,
          onChange: onSelectChange,
        }}
        columns={[
          ...columns,
          {
            title: '操作',
            dataIndex: 'action',
            key: 'action',
            width: 150,
            align: 'center',
            fixed: 'right',
            render: (_text: string, record: IUserInfo) => {
              return (
                <Space size={'small'}>
                  <Link onClick={() => setVisibleHandle(record)}>编辑</Link>
                  <PermissionButton
                    permission="SYSTEM_USER_DELETE"
                    type="link"
                    onClick={() => onDelete([record.userId])}>
                    删除
                  </PermissionButton>
                </Space>
              );
            },
          },
        ]}
        rowKey="userId"
        request={getUserList}
        left={
          <Button type="primary" onClick={() => setVisibleHandle()}>
            新增用户
          </Button>
        }
        right={
          <PermissionButton
            permission="SYSTEM_USER_DELETE"
            disabled={!selectedRowKeys.length}
            danger
            onClick={() => onDelete(selectedRowKeys as string[])}>
            批量删除
          </PermissionButton>
        }></Table>
      <UserModal
        width={800}
        maskClosable={false}
        data={data}
        open={visible}
        onOk={() => tableRef.current.onRefresh()}
        onCancel={setFalse}></UserModal>
    </div>
  );
}
